package org.jeecg.modules.wxchar.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.wxchar.util.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Api(tags="供需发布情况")
@RestController
@RequestMapping("/wx")
public class WxLoginController {
    // 过期时间60分钟
    public static final long EXPIRE_TIME = 60 * 60 * 1000;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ISysUserService sysUserService;
    private String appid = "wx69b5645056730faa";
    private String secret = "717176935ede19238d94cd555524f6b9";

    @RequestMapping("/wxLogin")
    public Object wxLogin(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> param = new HashMap<>();
        param.put("appid", appid);
        param.put("secret", secret);
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");
        // 发送请求
        String wxResult = HttpClientUtil.doGet(url, param);
        JSONObject jsonObject = JSONObject.parseObject(wxResult);
        // 获取参数返回的
        String session_key = jsonObject.get("session_key").toString();
        String open_id = jsonObject.get("openid").toString();
        //String session_key = "123456";
        //String open_id = "shan";
        //1. 校验用户是否有效
        SysUser sysUser = sysUserService.getUserByName(open_id);
        if(sysUser == null){
            sysUser = new SysUser();
            sysUser.setUsername(open_id);
            sysUser.setPassword(open_id);
            sysUser.setOpenId(open_id);
            sysUser.setStatus(1);
            sysUser.setDelFlag("0");
            sysUser.setCreateTime(new Date());//设置创建时间
            sysUserService.save(sysUser);
        }
        // 生成token

        String token = JwtUtil.sign(open_id, session_key);
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        // 设置超时时间
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, EXPIRE_TIME / 1000);

        return token;
    }
}
